package com.api.demo.watchface

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.ColorMatrix
import android.graphics.ColorMatrixColorFilter
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.RectF
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.support.wearable.watchface.CanvasWatchFaceService
import android.support.wearable.watchface.WatchFaceService
import android.support.wearable.watchface.WatchFaceStyle
import android.view.SurfaceHolder
import com.api.demo.R
import com.api.demo.gif.GifManagerRunnable
import com.api.demo.gif.GifManagerRunnable.OnFrameAvailable
import java.io.IOException
import java.io.InputStream
import java.lang.ref.WeakReference
import java.util.Calendar
import java.util.TimeZone
import java.util.concurrent.TimeUnit

/**
 * Analog watch face with a ticking second hand. In ambient mode, the second hand isn't
 * shown. On devices with low-bit ambient mode, the hands are drawn without anti-aliasing in ambient
 * mode. The watch face is drawn with less contrast in mute mode.
 *
 *
 * Important Note: Because watch face apps do not have a default Activity in
 * their project, you will need to set your Configurations to
 * "Do not launch Activity" for both the Wear and/or Application modules. If you
 * are unsure how to do this, please review the "Run Starter project" section
 * in the Google Watch Face Code Lab:
 * https://codelabs.developers.google.com/codelabs/watchface/index.html#0
 */
class GifWatchFace2 : CanvasWatchFaceService() {
    override fun onCreateEngine(): Engine {
        return Engine()
    }

    private class EngineHandler(reference: Engine) : Handler() {
        private val mWeakReference: WeakReference<Engine>

        init {
            mWeakReference = WeakReference(reference)
        }

        override fun handleMessage(msg: Message) {
            val engine = mWeakReference.get()
            if (engine != null) {
                when (msg.what) {
                    MSG_UPDATE_TIME -> engine.handleUpdateTimeMessage()
                }
            }
        }
    }

    inner class Engine : CanvasWatchFaceService.Engine() {
        /* Handler to update the time once a second in interactive mode. */
        private val mUpdateTimeHandler: Handler = EngineHandler(this)
        private var mCalendar: Calendar? = null
        private val mTimeZoneReceiver: BroadcastReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                mCalendar!!.timeZone = TimeZone.getDefault()
                invalidate()
            }
        }
        private var mRegisteredTimeZoneReceiver = false
        private var mMuteMode = false
        private var mCenterX = 0f
        private var mCenterY = 0f
        private val onFrameAvailable = OnFrameAvailable { bitmap ->
            mBackgroundBitmap = bitmap
            invalidate()
            bitmap
        }
        private var mBackgroundBitmap: Bitmap? = null
        private var mGrayBackgroundBitmap: Bitmap? = null
        private var mBackgroundPaint: Paint? = null
        private var mAmbient = false
        private var mLowBitAmbient = false
        private var mBurnInProtection = false
        override fun onCreate(holder: SurfaceHolder) {
            super.onCreate(holder)
            setWatchFaceStyle(
                WatchFaceStyle.Builder(this@GifWatchFace2)
                        .setAcceptsTapEvents(true)
                        .build()
            )
            mCalendar = Calendar.getInstance()
            initializeBackground()
            initializeWatchFace()
            try {
                var inputStream: InputStream? = null
                inputStream = applicationContext.assets.open("701.gif")
                val buffer = ByteArray(1024 * 500) //不超过500KB
                inputStream.read(buffer)
                inputStream.close()
                val gifManagerRunnable = GifManagerRunnable(buffer)
                gifManagerRunnable.setOuterFrameCallback(onFrameAvailable)
                gifManagerRunnable.startAnimation()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }

        private fun initializeBackground() {
            mBackgroundBitmap = BitmapFactory.decodeResource(resources, R.drawable.bg)
        }

        private fun initializeWatchFace() {
            /* Set defaults for colors */
            mBackgroundPaint = Paint()
        }

        override fun onDestroy() {
            mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME)
            super.onDestroy()
        }

        override fun onPropertiesChanged(properties: Bundle) {
            super.onPropertiesChanged(properties)
            mLowBitAmbient = properties.getBoolean(PROPERTY_LOW_BIT_AMBIENT, false)
            mBurnInProtection = properties.getBoolean(PROPERTY_BURN_IN_PROTECTION, false)
        }

        override fun onTimeTick() {
            super.onTimeTick()
            invalidate()
        }

        override fun onAmbientModeChanged(inAmbientMode: Boolean) {
            super.onAmbientModeChanged(inAmbientMode)
            mAmbient = inAmbientMode
            updateWatchHandStyle()

            /* Check and trigger whether or not timer should be running (only in active mode). */updateTimer()
        }

        private fun updateWatchHandStyle() {
            if (mAmbient) {
            } else {
            }
        }

        override fun onInterruptionFilterChanged(interruptionFilter: Int) {
            super.onInterruptionFilterChanged(interruptionFilter)
            val inMuteMode = interruptionFilter == INTERRUPTION_FILTER_NONE

            /* Dim display in mute mode. */if (mMuteMode != inMuteMode) {
                mMuteMode = inMuteMode
                invalidate()
            }
        }

        override fun onSurfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
            super.onSurfaceChanged(holder, format, width, height)

            /*
             * Find the coordinates of the center point on the screen, and ignore the window
             * insets, so that, on round watches with a "chin", the watch face is centered on the
             * entire screen, not just the usable portion.
             */mCenterX = width / 2f
            mCenterY = height / 2f

            /* Scale loaded background image (more efficient) if surface dimensions change. */
            val scale = width.toFloat() / mBackgroundBitmap!!.width.toFloat()
            mBackgroundBitmap = Bitmap.createScaledBitmap(
                mBackgroundBitmap!!,
                (mBackgroundBitmap!!.width * scale).toInt(),
                (mBackgroundBitmap!!.height * scale).toInt(),
                true
            )

            /*
             * Create a gray version of the image only if it will look nice on the device in
             * ambient mode. That means we don't want devices that support burn-in
             * protection (slight movements in pixels, not great for images going all the way to
             * edges) and low ambient mode (degrades image quality).
             *
             * Also, if your watch face will know about all images ahead of time (users aren't
             * selecting their own photos for the watch face), it will be more
             * efficient to create a black/white version (png, etc.) and load that when you need it.
             */if (!mBurnInProtection && !mLowBitAmbient) {
                initGrayBackgroundBitmap()
            }
        }

        private fun initGrayBackgroundBitmap() {
            mGrayBackgroundBitmap = Bitmap.createBitmap(
                mBackgroundBitmap!!.width,
                mBackgroundBitmap!!.height,
                Bitmap.Config.ARGB_8888
            )
            val canvas = Canvas(mGrayBackgroundBitmap!!)
            val grayPaint = Paint()
            val colorMatrix = ColorMatrix()
            colorMatrix.setSaturation(0f)
            val filter = ColorMatrixColorFilter(colorMatrix)
            grayPaint.setColorFilter(filter)
            canvas.drawBitmap(mBackgroundBitmap!!, 0f, 0f, grayPaint)
        }

        /**
         * Captures tap event (and tap type). The [WatchFaceService.TAP_TYPE_TAP] case can be
         * used for implementing specific logic to handle the gesture.
         */
        override fun onTapCommand(tapType: Int, x: Int, y: Int, eventTime: Long) {
            when (tapType) {
                TAP_TYPE_TOUCH -> {}
                TAP_TYPE_TOUCH_CANCEL -> {}
                TAP_TYPE_TAP -> {}
            }
            invalidate()
        }

        override fun onDraw(canvas: Canvas, bounds: Rect) {
            val now = System.currentTimeMillis()
            mCalendar!!.timeInMillis = now
            drawBackground(canvas)
            drawWatchFace(canvas)
        }

        private fun drawBackground(canvas: Canvas) {
//            if (mAmbient && (mLowBitAmbient || mBurnInProtection)) {
//                canvas.drawColor(Color.BLACK);
//            } else if (mAmbient) {
//
//            } else {
////                canvas.drawBitmap(mBackgroundBitmap, 0, 0, mBackgroundPaint);
//            }
        }

        private fun drawWatchFace(canvas: Canvas) {
            mBackgroundPaint!!.color = Color.WHITE
            val rectF = RectF(0f, 0f, mCenterX * 2, mCenterY * 2)
            canvas.drawRect(rectF, mBackgroundPaint!!)
            canvas.drawBitmap(
                mBackgroundBitmap!!, mCenterX - mBackgroundBitmap!!.width / 2,
                mCenterY - mBackgroundBitmap!!.height / 2, mBackgroundPaint
            )

            /*
             * Ensure the "seconds" hand is drawn only when we are in interactive mode.
             * Otherwise, we only update the watch face once a minute.
             */if (!mAmbient) {
            }

        }

        override fun onVisibilityChanged(visible: Boolean) {
            super.onVisibilityChanged(visible)
            if (visible) {
                registerReceiver()
                /* Update time zone in case it changed while we weren't visible. */mCalendar!!.timeZone =
                    TimeZone.getDefault()
                invalidate()
            } else {
                unregisterReceiver()
            }

            /* Check and trigger whether or not timer should be running (only in active mode). */updateTimer()
        }

        private fun registerReceiver() {
            if (mRegisteredTimeZoneReceiver) {
                return
            }
            mRegisteredTimeZoneReceiver = true
            val filter = IntentFilter(Intent.ACTION_TIMEZONE_CHANGED)
            this@GifWatchFace2.registerReceiver(mTimeZoneReceiver, filter)
        }

        private fun unregisterReceiver() {
            if (!mRegisteredTimeZoneReceiver) {
                return
            }
            mRegisteredTimeZoneReceiver = false
            this@GifWatchFace2.unregisterReceiver(mTimeZoneReceiver)
        }

        /**
         * Starts/stops the [.mUpdateTimeHandler] timer based on the state of the watch face.
         */
        private fun updateTimer() {
            mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME)
            if (shouldTimerBeRunning()) {
                mUpdateTimeHandler.sendEmptyMessage(MSG_UPDATE_TIME)
            }
        }

        /**
         * Returns whether the [.mUpdateTimeHandler] timer should be running. The timer
         * should only run in active mode.
         */
        private fun shouldTimerBeRunning(): Boolean {
            return isVisible && !mAmbient
        }

        /**
         * Handle updating the time periodically in interactive mode.
         */
        fun handleUpdateTimeMessage() {
            invalidate()
            if (shouldTimerBeRunning()) {
                val timeMs = System.currentTimeMillis()
                val delayMs = INTERACTIVE_UPDATE_RATE_MS - timeMs % INTERACTIVE_UPDATE_RATE_MS
                mUpdateTimeHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIME, delayMs)
            }
        }
    }

    companion object {
        /*
     * Updates rate in milliseconds for interactive mode. We update once a second to advance the
     * second hand.
     */
        private val INTERACTIVE_UPDATE_RATE_MS = TimeUnit.SECONDS.toMillis(1)

        /**
         * Handler message id for updating the time periodically in interactive mode.
         */
        private const val MSG_UPDATE_TIME = 0
    }
}
